<template>
  <div>
    <a-modal
      title="选择部门"
      :visible="visible"
      :confirm-loading="loading"
      class="normal-modal"
      @ok="handleOk"
      @cancel="$emit('update:visible', false)"
    >
      <a-spin :spinning="spinning">
        <a-row>
          <a-col :span="24">
            <a-tree
              style="height: 400px; overflow: auto"
              :selected-keys.sync="selectedKeys"
              :replace-fields="replaceFields"
              :expanded-keys.sync="expandedKeys"
              :tree-data="orgTreeData"
              @select="getOrgPerson"
            />
          </a-col>
        </a-row>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getCustOrgTree } from '@/api/subassembly/TreeSelectOrganization'

/*
 * 弹窗选择全部部门，不支持指定单位展示
 *
 * */
export default {
  name: 'DialogSelectDepartment',
  props: {
    // 显隐
    visible: {
      type: Boolean,
      required: true
    },
    // 请求参数
    orgQuery: {
      type: Object,
      default: () => null
    },
    // 可以选择的部门层级:公司部门 CO；分公司部门 BC;项目部门 PD
    level: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      loading: false,
      selectedKeys: [],
      orgTreeData: [],
      replaceFields: {
        children: 'children',
        title: 'label',
        key: 'id'
      },
      spinning: false,
      selectRow: null,
      allList: [],
      expandedKeys: [] // 展开节点枚举
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.expandedKeys = []
        this.allList = []
        this.spinning = true
             // 获取组织机构
        let params = {
            baseOrgType:0,
            types: "1,2,3,7,8"
          }
        getCustOrgTree(this.orgQuery ? this.orgQuery :params)
          .then((res) => {
            this.spinning = false
            if (res.data?.length > 0) {
              this.formatList(res.data)
              this.orgTreeData = res.data
            }
          })
          .catch(() => {
            this.spinning = false
          })
      }
    }
  },

  methods: {
    /**
     * 遍历父节点设置其为显示
     */
    setParent(item) {
      for (let index in this.allList) {
        let i = this.allList[index]
        if (i[this.replaceFields.key] === item.pid) {
          i.style && delete this.allList[index].style
          if (i.pid) this.setParent(this.allList[index])
          return
        }
      }
    },
    /**
     * 格式化列表
     */
    formatList(list = []) {
      for (let item of list) {
        this.allList.push(item)
        // 若要根据层级筛选部门
        if (this.level) {
          for (let code of ['CO', 'BC', 'PD']) {
            if (this.level === code) {
              let pid = {
                CO: this.$userInfo()?.employee?.levels?.find((i) => i.code === code)?.id || '53085e2c9f1f4685801ef31994f57c49',
                BC: this.$currentPost().orgId,
                PD: this.$currentPost().id
              }[code] // 登陆人所属组织
              // 禁用除登陆人所属组织部门以外部门
              if (!item.children && pid === item.pid) {
                item.disabled = false
                // 显示节点
                item.style && delete item.style
                // 显示上级节点
                this.setParent(item)
              } else {
                item.disabled = true
                // 隐藏节点
                item.style = { display: 'none' }
                // 若有子级继续遍历
                if (item.children?.length > 0) {
                  //   默认展开父节点
                  this.expandedKeys.push(item[this.replaceFields.key])
                  this.formatList(item.children)
                }
              }
            }
          }
        } else {
          // 根据是否是部门（树最后一级）设置树选项禁用状态
          item.disabled = item.children ? true : false
          item.style && delete item.style
          // 若有子级继续遍历
          if (item.children?.length > 0) {
            //   默认展开父节点
            this.expandedKeys.push(item[this.replaceFields.key])
            this.formatList(item.children)
          }
        }
      }
    },
    handleOk() {
      if (!this.selectRow) {
        return this.$noticeWarning('请选择部门！')
      }
      this.$emit('update:visible', false)
      this.$emit('ok', this.selectRow)
    },
    getOrgPerson(selectedKeys, info) {
      if (selectedKeys.length) {
        let props = info.selectedNodes[0].data.props
        if (!props.dataRef.children) {
          this.selectedKeys = selectedKeys
          this.selectRow = props
        } else {
          this.selectedKeys = []
          this.$noticeWarning('只能选择部门！')
        }
      } else {
        this.selectedKeys = []
      }
    }
  }
}
</script>

<style lang='less' scoped>
</style>
